import Orchestrator from "@/logic/audioOrchestrator";

export function useChatWS() {
  // 为了兼容你以前的调用，这里提供简易 connect/disconnect 和发配置等
  var WS_URL = "ws://192.168.1.153:8000/ws/chat";
  var ws = null, status="idle", lastError="", lastMsg=null;

  function getToken() {
    var raw = localStorage.getItem("token") || "";
    raw = String(raw).trim();
    if (!raw || raw === "null" || raw === "undefined" || raw === "None") return "";
    return raw.toLowerCase().startsWith("bearer ") ? raw : ("Bearer " + raw);
  }
  function makeUrl() {
    var t = getToken();
    return t ? (WS_URL + "?token=" + encodeURIComponent(t)) : WS_URL;
  }
  function send(obj){ if (ws && ws.readyState===WebSocket.OPEN) { try{ ws.send(JSON.stringify(obj)); }catch(e){} } }

  function connect() {
    if (ws && (ws.readyState===WebSocket.OPEN || ws.readyState===WebSocket.CONNECTING)) return;
    var token = getToken(); if (!token) { status="blocked"; lastError="缺少令牌"; return; }
    ws = new WebSocket(makeUrl());
    ws.onopen = function(){ status="open"; };
    ws.onclose= function(){ status="closed"; ws=null; };
    ws.onerror= function(){};
    ws.onmessage = function(ev){
      try { lastMsg = JSON.parse(ev.data); } catch(e){ return; }
      if (lastMsg && lastMsg.type==="danmu_event" && lastMsg.data) {
        // 交给 Orchestrator 内部限流+合成（你也可以删掉这行，改用 Orchestrator.connectChat() 自己连）
        // 这里不做额外处理，兼容外部 UI 使用 lastMsg
      }
    };
  }
  function disconnect(){ try{ ws && ws.close(1000,"normal"); }catch(e){} ws=null; status="closed"; }

  return {
    get wsStatus(){ return status; },
    get lastError(){ return lastError; },
    get lastMsg(){ return lastMsg; },
    connect, disconnect,

    // 业务发包（兼容你以前的按钮）
    sendDanmu: function(id){ send({type:"danmu", data:{id:String(id||"")}}); },
    sendGetUserInfo: function(){ send({type:"gu"}); },
    sendGetUserConfig: function(){ send({type:"gc"}); },
    sendSetUserConfig: function(data){ send({type:"uc", data:data||{}}); },
  };
}
